<template>
  <div class="models-page">
    <div class="page-header">
      <h1 class="page-title">🤖 模型管理</h1>
      <p class="page-description">管理您的AI模型连接，支持Ollama和OpenAI兼容接口</p>
    </div>

    <!-- 添加/编辑模型表单 -->
    <div class="model-form-card">
      <div class="card-header">
        <h2>{{ isEditing ? '编辑模型' : '添加新模型' }}</h2>
      </div>
      <form @submit.prevent="addOrUpdateModel" class="model-form">
        <div class="form-row">
          <div class="form-group">
            <label>模型名称</label>
            <input 
              v-model="currentModel.name" 
              placeholder="输入模型名称" 
              required
              class="form-input"
            >
          </div>
          <div class="form-group">
            <label>模型类型</label>
            <select v-model="currentModel.type" required class="form-select">
              <option value="ollama">Ollama</option>
              <option value="openai">OpenAI Compatible</option>
            </select>
          </div>
        </div>
        
        <div class="form-group">
          <label>Base URL</label>
          <div class="input-with-button">
            <input 
              v-model="currentModel.baseUrl" 
              placeholder="http://localhost:11434" 
              required
              class="form-input"
            >
            <button 
              type="button" 
              @click="detectModels" 
              :disabled="!currentModel.baseUrl || isDetecting"
              class="detect-btn"
            >
              {{ isDetecting ? '检测中...' : '检测模型' }}
            </button>
          </div>
        </div>
        
        <div class="form-group">
          <label>API Key (可选)</label>
          <input 
            v-model="currentModel.apiKey" 
            placeholder="输入API密钥" 
            type="password"
            class="form-input"
          >
        </div>

        <!-- 检测到的模型列表 -->
        <div v-if="detectedModels.length > 0" class="detected-models">
          <h3>检测到的模型:</h3>
          <div class="model-chips">
            <span 
              v-for="model in detectedModels" 
              :key="model"
              class="model-chip"
              @click="selectDetectedModel(model)"
            >
              {{ model }}
            </span>
          </div>
        </div>

        <div class="form-actions">
          <button type="submit" class="btn btn-primary" :disabled="isSubmitting">
            {{ isSubmitting ? '处理中...' : (isEditing ? '更新模型' : '添加模型') }}
          </button>
          <button v-if="isEditing" type="button" @click="cancelEdit" class="btn btn-secondary">
            取消
          </button>
        </div>
      </form>
    </div>

    <!-- 模型列表 -->
    <div class="models-grid">
      <div v-if="models.length === 0" class="empty-state">
        <div class="empty-icon">🤖</div>
        <h3>暂无模型</h3>
        <p>添加您的第一个AI模型开始使用</p>
      </div>
      
      <div v-for="model in models" :key="model.id" class="model-card">
        <div class="model-header">
          <div class="model-info">
            <h3 class="model-name">{{ model.name }}</h3>
            <span class="model-type" :class="model.type">{{ model.type.toUpperCase() }}</span>
          </div>
          <div class="model-status">
            <span class="status-dot" :class="getModelStatus(model)"></span>
            <span class="status-text">{{ getModelStatusText(model) }}</span>
          </div>
        </div>
        
        <div class="model-details">
          <div class="detail-item">
            <span class="label">Base URL:</span>
            <span class="value">{{ model.baseUrl }}</span>
          </div>
          <div class="detail-item" v-if="model.apiKey">
            <span class="label">API Key:</span>
            <span class="value">••••••••</span>
          </div>
        </div>
        
        <div class="model-actions">
          <button @click="testModel(model)" class="btn btn-test" :disabled="isTestingModel === model.id">
            {{ isTestingModel === model.id ? '测试中...' : '测试连接' }}
          </button>
          <button @click="editModel(model)" class="btn btn-edit">
            编辑
          </button>
          <button @click="deleteModel(model.id)" class="btn btn-delete">
            删除
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      models: [],
      currentModel: {
        name: '',
        type: 'ollama',
        baseUrl: '',
        apiKey: ''
      },
      isEditing: false,
      editingId: null,
      isDetecting: false,
      isSubmitting: false,
      isTestingModel: null,
      detectedModels: [],
      modelStatuses: {}
    };
  },
  async mounted() {
    await this.fetchModels();
  },
  methods: {
    async fetchModels() {
      try {
        const response = await fetch('/api/models');
        this.models = await response.json();
      } catch (error) {
        console.error('Error fetching models:', error);
        this.$message?.error('获取模型列表失败');
      }
    },
    async detectModels() {
      if (!this.currentModel.baseUrl) return;
      
      this.isDetecting = true;
      this.detectedModels = [];
      
      try {
        const response = await fetch('/api/detect-models', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            baseUrl: this.currentModel.baseUrl,
            type: this.currentModel.type,
            apiKey: this.currentModel.apiKey
          })
        });
        
        if (response.ok) {
          const result = await response.json();
          this.detectedModels = result.models || [];
          if (this.detectedModels.length === 0) {
            this.$message?.warning('未检测到可用模型');
          } else {
            this.$message?.success(`检测到 ${this.detectedModels.length} 个模型`);
          }
        } else {
          const error = await response.json();
          this.$message?.error(error.message || '模型检测失败');
        }
      } catch (error) {
        console.error('Error detecting models:', error);
        this.$message?.error('连接失败，请检查URL和网络');
      } finally {
        this.isDetecting = false;
      }
    },
    selectDetectedModel(modelName) {
      this.currentModel.name = modelName;
    },
    async testModel(model) {
      this.isTestingModel = model.id;
      
      try {
        const response = await fetch('/api/test-model', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            id: model.id
          })
        });
        
        if (response.ok) {
          const result = await response.json();
          this.modelStatuses[model.id] = result.status;
          this.$message?.success('连接测试成功');
        } else {
          const error = await response.json();
          this.modelStatuses[model.id] = 'error';
          this.$message?.error(error.message || '连接测试失败');
        }
      } catch (error) {
        console.error('Error testing model:', error);
        this.modelStatuses[model.id] = 'error';
        this.$message?.error('连接测试失败');
      } finally {
        this.isTestingModel = null;
      }
    },
    async addOrUpdateModel() {
      this.isSubmitting = true;
      
      try {
        const method = this.isEditing ? 'PUT' : 'POST';
        const url = this.isEditing ? `/api/models/${this.editingId}` : '/api/models';
        
        const response = await fetch(url, {
          method,
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(this.currentModel)
        });
        
        if (response.ok) {
          await this.fetchModels();
          this.resetForm();
          this.$message?.success(this.isEditing ? '模型更新成功' : '模型添加成功');
        } else {
          const error = await response.json();
          this.$message?.error(error.message || '操作失败');
        }
      } catch (error) {
        console.error('Error saving model:', error);
        this.$message?.error('操作失败，请重试');
      } finally {
        this.isSubmitting = false;
      }
    },
    async deleteModel(id) {
      if (!confirm('确定要删除这个模型吗？')) return;
      
      try {
        const response = await fetch(`/api/models/${id}`, {
          method: 'DELETE'
        });
        
        if (response.ok) {
          await this.fetchModels();
          this.$message?.success('模型删除成功');
        } else {
          const error = await response.json();
          this.$message?.error(error.message || '删除失败');
        }
      } catch (error) {
        console.error('Error deleting model:', error);
        this.$message?.error('删除失败，请重试');
      }
    },
    editModel(model) {
      this.currentModel = { ...model };
      this.isEditing = true;
      this.editingId = model.id;
      this.detectedModels = [];
    },
    cancelEdit() {
      this.resetForm();
    },
    resetForm() {
      this.currentModel = {
        name: '',
        type: 'ollama',
        baseUrl: '',
        apiKey: ''
      };
      this.isEditing = false;
      this.editingId = null;
      this.detectedModels = [];
    },
    getModelStatus(model) {
      const status = this.modelStatuses[model.id];
      if (status === 'success') return 'online';
      if (status === 'error') return 'offline';
      return 'unknown';
    },
    getModelStatusText(model) {
      const status = this.modelStatuses[model.id];
      if (status === 'success') return '在线';
      if (status === 'error') return '离线';
      return '未知';
    }
  }
};
</script>

<style scoped>
.models-page {
  padding: 24px;
  max-width: 1200px;
  margin: 0 auto;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  min-height: 100vh;
}

.page-header {
  text-align: center;
  margin-bottom: 32px;
  color: white;
}

.page-title {
  font-size: 2.5rem;
  font-weight: 700;
  margin: 0 0 8px 0;
  text-shadow: 0 2px 4px rgba(0,0,0,0.3);
}

.page-description {
  font-size: 1.1rem;
  opacity: 0.9;
  margin: 0;
}

.model-form-card {
  background: white;
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0,0,0,0.1);
  margin-bottom: 32px;
  overflow: hidden;
}

.card-header {
  background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);
  color: white;
  padding: 20px 24px;
  margin: 0;
}

.card-header h2 {
  margin: 0;
  font-size: 1.5rem;
  font-weight: 600;
}

.model-form {
  padding: 24px;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
  margin-bottom: 16px;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 6px;
  font-weight: 500;
  color: #374151;
  font-size: 0.9rem;
}

.form-input, .form-select {
  width: 100%;
  padding: 12px 16px;
  border: 2px solid #e5e7eb;
  border-radius: 8px;
  font-size: 1rem;
  transition: all 0.2s ease;
  box-sizing: border-box;
}

.form-input:focus, .form-select:focus {
  outline: none;
  border-color: #4f46e5;
  box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
}

.input-with-button {
  display: flex;
  gap: 8px;
}

.input-with-button .form-input {
  flex: 1;
}

.detect-btn {
  padding: 12px 20px;
  background: linear-gradient(135deg, #10b981 0%, #059669 100%);
  color: white;
  border: none;
  border-radius: 8px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  white-space: nowrap;
}

.detect-btn:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);
}

.detect-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.detected-models {
  margin-top: 16px;
  padding: 16px;
  background: #f8fafc;
  border-radius: 8px;
  border: 1px solid #e2e8f0;
}

.detected-models h3 {
  margin: 0 0 12px 0;
  color: #374151;
  font-size: 1rem;
}

.model-chips {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.model-chip {
  padding: 6px 12px;
  background: #4f46e5;
  color: white;
  border-radius: 20px;
  font-size: 0.875rem;
  cursor: pointer;
  transition: all 0.2s ease;
}

.model-chip:hover {
  background: #4338ca;
  transform: translateY(-1px);
}

.form-actions {
  display: flex;
  gap: 12px;
  margin-top: 24px;
}

.btn {
  padding: 12px 24px;
  border: none;
  border-radius: 8px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 1rem;
}

.btn-primary {
  background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);
  color: white;
}

.btn-primary:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(79, 70, 229, 0.3);
}

.btn-secondary {
  background: #6b7280;
  color: white;
}

.btn-secondary:hover {
  background: #4b5563;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.models-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 24px;
}

.empty-state {
  grid-column: 1 / -1;
  text-align: center;
  padding: 48px 24px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 16px rgba(0,0,0,0.1);
}

.empty-icon {
  font-size: 4rem;
  margin-bottom: 16px;
}

.empty-state h3 {
  color: #374151;
  margin: 0 0 8px 0;
}

.empty-state p {
  color: #6b7280;
  margin: 0;
}

.model-card {
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 16px rgba(0,0,0,0.1);
  overflow: hidden;
  transition: all 0.3s ease;
}

.model-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 32px rgba(0,0,0,0.15);
}

.model-header {
  padding: 20px;
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
  border-bottom: 1px solid #e2e8f0;
}

.model-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.model-name {
  margin: 0;
  color: #1f2937;
  font-size: 1.25rem;
  font-weight: 600;
}

.model-type {
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 0.75rem;
  font-weight: 600;
  text-transform: uppercase;
}

.model-type.ollama {
  background: #dbeafe;
  color: #1e40af;
}

.model-type.openai {
  background: #dcfce7;
  color: #166534;
}

.model-status {
  display: flex;
  align-items: center;
  gap: 6px;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
}

.status-dot.online {
  background: #10b981;
}

.status-dot.offline {
  background: #ef4444;
}

.status-dot.unknown {
  background: #6b7280;
}

.status-text {
  font-size: 0.875rem;
  color: #6b7280;
}

.model-details {
  padding: 20px;
}

.detail-item {
  display: flex;
  margin-bottom: 8px;
}

.detail-item:last-child {
  margin-bottom: 0;
}

.detail-item .label {
  font-weight: 500;
  color: #6b7280;
  min-width: 80px;
  font-size: 0.875rem;
}

.detail-item .value {
  color: #374151;
  font-size: 0.875rem;
  word-break: break-all;
}

.model-actions {
  padding: 16px 20px;
  background: #f9fafb;
  display: flex;
  gap: 8px;
  border-top: 1px solid #e5e7eb;
}

.btn-test {
  background: linear-gradient(135deg, #10b981 0%, #059669 100%);
  color: white;
  padding: 8px 16px;
  font-size: 0.875rem;
}

.btn-edit {
  background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
  color: white;
  padding: 8px 16px;
  font-size: 0.875rem;
}

.btn-delete {
  background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
  color: white;
  padding: 8px 16px;
  font-size: 0.875rem;
}

.btn-test:hover:not(:disabled),
.btn-edit:hover,
.btn-delete:hover {
  transform: translateY(-1px);
}

@media (max-width: 768px) {
  .models-page {
    padding: 16px;
  }
  
  .form-row {
    grid-template-columns: 1fr;
  }
  
  .models-grid {
    grid-template-columns: 1fr;
  }
  
  .input-with-button {
    flex-direction: column;
  }
  
  .model-actions {
    flex-direction: column;
  }
}
</style>